<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image>
      <text class="title">机房巡检</text>
    </view>
    <view class="login-form-content">
      <view class="action-btn">
		<button 
			class="login-btn cu-btn block bg-blue lg round" 
			open-type="getPhoneNumber"
			@getphonenumber="getPhoneNumber">
			一键授权手机号并登录
		</button>
		
		<button
			class="login-btn cu-btn block lg round mask-btn" 
			@click="handleLogin"
			v-if="!isAgree">
		</button>
		  
		<checkbox-group class="checkbox-container" @change="checkboxChange">
			<view class="myCheckbox">
				<checkbox
					style="transform: scale(0.5)"
					:checked="policyChecked"
					:value="true"
					class="round green"
				></checkbox>
				<view 
					class="title text-black" 
					style="margin-right: 5rpx; text-decoration: underline"
					@click="touchProtocol"
					>
					同意（机房巡检）服务协议与隐私政策
				</view>
			</view>
<!-- 			<label>
				<checkbox 
				:checked="policyChecked" 
				class="round black"
				/>同意（机房巡检）服务协议与隐私政策
			</label> -->
		</checkbox-group>
      </view>
    </view>
  </view>
</template>

<script>
	export default {
		data() {
			return {
				globalConfig: getApp().globalData.config,
				policy: 0,
				policyChecked: false,
				text_login: '',
				text_user: '',
				isAgree: false,
			}
		},
		methods: {
			// 登录方法
			async handleLogin() {
				// 1.先判断是否同意协议
				if(this.policy != 1) {					
					uni.showToast({
						title: '请同意用户服务协议与隐私政策',
						icon: 'none',
						duration: 2000
					});
				}
				
				// // 2.调用WX的code
				// this.weixinLogin();
			},
			
			checkboxChange(e){
				if(e.detail.value.length==1){
					this.checked = true,
					this.policy = 1,
					this.isAgree = true
				}else{
					this.checked = false,
					this.policy = 0,
					this.isAgree = false
				}
			},
			
			// 处理实际微信登录, 系统已经注册的用户就直接登录，没有就跳转去注册
			getLogin() {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.login({
						provider:'weixin',
						success(res) {
							resolve(res)
							that.text_login = 
								"  code：  " + res.code 
								+ "  -errMsg：  " + res.errMsg
							// console.log(that.text_login, 'login')
							console.log(res, 'login')
						},
						fail: (err) => {
							console.log(err, 'logoer')
							reject(err)
						}
					})
				})
			},
			
			getUserInfo() {
				let that = this;
				return new Promise((resolve, reject) => {
					uni.getUserProfile({
						lang: 'zh_CN',
						desc: '用户登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，
						success: (res) => {
							resolve(res.userInfo)
							that.text_user = 
								"  cloudID：  " + res.cloudID 
								+ "  -encryptedData：  " + res.encryptedData 
								+ "  -errMsg：  " + res.errMsg 
								+ "  -iv：  " + res.iv 
								+ "  -rawData:  " + res.rawData 
								+ "  -signature:  " + res.signature 
								+ "  -userInfo.avatarUrl:  " + res.userInfo.avatarUrl
								+ "  -userInfo.city:  " + res.userInfo.city
								+ "  -userInfo.country:  " + res.userInfo.country
								+ "  -userInfo.gender:  " + res.userInfo.gender
								+ "  -userInfo.is_demote:  " + res.userInfo.is_demote
								+ "  -userInfo.language:  " + res.userInfo.language
								+ "  -userInfo.nickName:  " + res.userInfo.nickName
								+ "  -userInfo.province:  " + res.userInfo.province
								
							// console.log(that.text_user, 'userinfo')
							console.log(res, 'userinfo')
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			
			// 微信认证登录
			weixinLogin() {
				let that = this;
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						//支持微信、qq和微博等
						if (~res.provider.indexOf('weixin')) {
							console.log(res, 'provider')
							let userInfo = that.getUserInfo();
							let loginRes = that.getLogin();
			// 				Promise.all([userInfo, loginRes]).then((result) =>{
			// 					let userInfo = result[0];
			// 					let loginRes = result[1];
			// 					let access_token = loginRes.authResult.access_token;
			// 					let openid = loginRes.authResult.openid;
			// 					let data = Object.assign(loginRes.authResult, userInfo);
								
			// 					console.log(data);
								
			// 					// that.$store.dispatch('Login', {
			// 					// 		type: 'weixin',
			// 					// 		url: that.url,
			// 					// 		data
			// 					// }).then(r => {
			// 					// 		if (r == 'ok') {
			// 					// 			uni.hideLoading()
			// 					// 		}
			// 					// 		}).catch(err => {
			// 					// 			uni.hideLoading();
			// 					// 			uni.showToast({
			// 					// 				icon: 'none',
			// 					// 				title: err
			// 					// 		})
			// 					// 	})
		 
			// 				})
						}
					},
					fail: function(err) {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: err
						})
					}
				})
			},
			

			/**
			 * 使用场景：
			 * 1.用户点击并同意之后，通过 bindgetphonenumber 事件获取回调信息
			 * 2.用户不同意，就直接退出即可
			 * @param {Object} e
			 */
			getPhoneNumber(e) {
				// console.log(e);
				// let loginRes = this.getLogin();
				
				// 当用户确认后，拿到对应的 code
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') { 
					//用户点击拒绝
					// that.hideModal();
				} else { 
					//允许授权执行跳转
					this.WXLogin(e.detail.code, null);
					
					// 1.判断用户是否已经拿到 token ，没有就去注册
					
				}
			},
			
			
			// 微信一键登录 
			async WXLogin(code) {
			  this.$store.dispatch(
				'WXLogin', 
				code
			  ).then(result => {
				// 来到回调函数
				this.jumpTo(result)
				
				// this.$modal.closeLoading()
			  }).catch(result  => {
			    // 无法获取到用户手机号
				
			  })
			},
			

			/**
			 * 跳转操作
			 * 1.拿到 token 直接登录
			 * 2.没有 token 就去注册
			 * @param {Object} res
			 */
			jumpTo(res) {
				
				console.log(res)
				// 1.拿到的 res 包含 Register, 就去注册
				if(undefined != res.Register) {
					this.$tab.redirectTo(
					`/pages/register?phone=`+res.Register
					)
				}else {
					// 2.拿到 res 不包含 Register, 就去登录
					this.loginSuccess()
				}
			},
			
			// 登录成功后，处理函数
			loginSuccess(result) {
			  // 设置用户信息
			  this.$store.dispatch('GetInfo').then(res => {
			    this.$tab.reLaunch('/pages/index')
			  })
			},
			
			// 用户确定服务条款
			touchProtocol() {
				this.$tab.redirectTo(`/pages/protocol`)
			}
		}
	}
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }

  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 15%;

      image {
        border-radius: 4px;
      }

      .title {
        margin-left: 10px;
      }
    }

    .login-form-content {
	  position: relative;
      text-align: center;
      margin: 20px auto;
      margin-top: 15%;
      width: 80%;

      .action-btn {
		  margin-top: 180px;
	  }
	  
	  .checkbox-container {
		  width: 100%;
		  position: absolute;
		  top: 60px;
		  left: 8px;
		  
		  .myCheckbox {
			  width: 100%;
		  }
		  
		  .myCheckbox ::v-deep .round {
			  // position: absolute;
			  // top: -4px;
			  // display: inline;
			  border: 3px solid #000;
		  }
		  
		  .myCheckbox ::v-deep .text-black{
			  position: absolute;
			  top: 2px;
			  left: 8%;
		  }
	  }
	  
	  .checkbox-container ::v-deep checkbox {
		  top: -4px !important;
		  left: -48%;
		  // display: inline;
	  }
	  
	  .mask-btn {
		  top: -50px;
		  height: 120rpx;
		  background-color: transparent; /* 设置背景为透明 */
		  border: none; /* 设置边框为无 */
	  }
    }
  }
</style>
